package com.rpc.client;


import com.rpc.codec.RpcResponse;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.net.SocketAddress;


/**
 * @Description 业务处理器
 * @Author 顾志杰
 * @Date 2022/2/28 10:08
 */
public class RpcClientHandler extends SimpleChannelInboundHandler<RpcResponse> {

  private Channel channel;

  private SocketAddress remotePeer;

  /**
   * 通道注册的时候触发此方法
   */
  public void channelRegistered(ChannelHandlerContext ctx) throws Exception{
    super.channelRegistered(ctx);
    this.channel = ctx.channel();
  }

  /**
   * 通道激活的时候触发此方法
   */
  public void channelActive(ChannelHandlerContext ctx) throws Exception{
      super.channelActive(ctx);
      this.remotePeer = this.channel.remoteAddress();
  }


  /**
   * 处理业务的方法
   * @param ctx
   * @param rpcResponse
   * @throws Exception
   */
  @Override
  protected void channelRead0(ChannelHandlerContext ctx, RpcResponse rpcResponse) throws Exception {

  }

  public SocketAddress getRemotePeer() {
    return this.remotePeer;
  }

  /**
   * Netty 提供了一种主动关闭连接的方式 发送一个Unpooled.EMPTY_BUFFER 这样我们的ChannelFutureListener的close事件就会监听到并关闭通道
   */
  public void close() {
    channel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
  }
}
